// task_create_add_image_text_page.dart
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:oktoast/oktoast.dart';
import 'package:sjx/repository/sjx_api.dart';

import '../model/task_step_model.dart';


class TaskCreateAddLinkPage extends StatefulWidget {
  final TaskStepModel? object;

  const TaskCreateAddLinkPage({
    super.key,
    this.object,
  });

  @override
  _TaskCreateAddLinkPageState createState() => _TaskCreateAddLinkPageState();
}

class _TaskCreateAddLinkPageState extends State<TaskCreateAddLinkPage> {
  final TextEditingController _explainController = TextEditingController();
  final TextEditingController _linkController = TextEditingController();

  bool _isEditing = false;

  @override
  void initState() {
    super.initState();
    _initializeData();
  }

  void _initializeData() {
    if (widget.object != null) {
      // 编辑模式
      _explainController.text = widget.object!.taskDescription;
      _linkController.text = widget.object!.taskLinks!;
      _isEditing = false;
    } else {
      // 新增模式
      _isEditing = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('添加网址链接'),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: _onBackPressed,
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.save),
            onPressed: _saveData,
          ),
        ],
      ),
      body: _buildBody(),
      bottomNavigationBar: _buildBottomButton(),
    );
  }

  Widget _buildBody() {
    return SingleChildScrollView(
      padding: const EdgeInsets.only(top: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 文字说明标题
          _buildSectionTitle('网址链接说明（必填）'),
          const SizedBox(height: 8),

          // 文字输入框
          _buildExplainTextField(),
          const SizedBox(height: 24),

          // 图片说明标题
          _buildSectionTitle('网址链接（必填，用户支持点击访问）'),
          const SizedBox(height: 8),

          // 文字输入框
          _buildLinkTextField(),
        ],
      ),
    );
  }

  Widget _buildSectionTitle(String title) {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.only(left: 16, top: 8, bottom: 8),
      decoration: BoxDecoration(
        color: const Color(0xFFF5F7FA),
        borderRadius: BorderRadius.circular(4),
      ),
      child: Text(
        title,
        style: const TextStyle(
          fontSize: 13,
          color: Color(0xFF666666),
        ),
      ),
    );
  }

  Widget _buildExplainTextField() {
    return Container(
        padding: const EdgeInsets.only(left: 16, right: 16),
        child: TextField(
          controller: _explainController,
          maxLines: 5,
          minLines: 5,
          decoration: InputDecoration(
            hintText: '请输入打开网址的注意事项',
            hintStyle: const TextStyle(fontSize: 14, color: Color(0xFF999999)),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(4),
              borderSide: const BorderSide(color: Color(0xFFDDDDDD)), // 这里设置颜色
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(4),
              borderSide: const BorderSide(color: Colors.blue), // 聚焦时的颜色
            ),
            contentPadding: const EdgeInsets.all(12),
            filled: true,
            fillColor: Colors.white,
          ),
          onChanged: (value) {
            setState(() {
              _isEditing = true;
            });
          },
        )
    );
  }

  Widget _buildLinkTextField() {
    return Container(
        padding: const EdgeInsets.only(left: 16, right: 16),
        child: TextField(
          controller: _linkController,
          maxLines: 5,
          minLines: 5,
          decoration: InputDecoration(
            hintText: '请输入任务相关链接：https://或http://',
            hintStyle: const TextStyle(fontSize: 14, color: Color(0xFF999999)),
            enabledBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(4),
              borderSide: const BorderSide(color: Color(0xFFDDDDDD)), // 这里设置颜色
            ),
            focusedBorder: OutlineInputBorder(
              borderRadius: BorderRadius.circular(4),
              borderSide: const BorderSide(color: Colors.blue), // 聚焦时的颜色
            ),
            contentPadding: const EdgeInsets.all(12),
            filled: true,
            fillColor: Colors.white,
          ),
          onChanged: (value) {
            setState(() {
              _isEditing = true;
            });
          },
        )
    );
  }



  Widget _buildBottomButton() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(top: BorderSide(color: Colors.grey[300]!)),
      ),
      child: ElevatedButton(
        onPressed: _saveData,
        style: ElevatedButton.styleFrom(
          backgroundColor: Theme.of(context).primaryColor,
          minimumSize: const Size(double.infinity, 44),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
        ),
        child: const Text(
          '确定',
          style: TextStyle(fontSize: 16, color: Colors.white),
        ),
      ),
    );
  }

  Future<void> _saveData() async {
    if (_explainController.text.isEmpty) {
      showToast('请输入链接说明内容');
      return;
    }
    if (_linkController.text.isEmpty) {
      showToast('请输入网址链接');
      return;
    }

    final taskStep = TaskStepModel(
      taskStepType: 'LINK',
      taskDescription: _explainController.text,
      taskLinks: _linkController.text,
      sortValue: widget.object?.sortValue,
    );
    Navigator.of(context).pop(taskStep);
  }

  void _onBackPressed() {
    if (_isEditing) {
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('提示'),
          content: const Text('是否放弃当前编辑？'),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: const Text('放弃'),
            ),
          ],
        ),
      );
    } else {
      Navigator.pop(context);
    }
  }

  @override
  void dispose() {
    _explainController.dispose();
    _linkController.dispose();
    super.dispose();
  }
}